package com.yl.androidutilscenter.http.gson

import com.google.gson.Gson
import com.google.gson.TypeAdapter
import com.google.gson.stream.JsonWriter
import okhttp3.MediaType
import okhttp3.RequestBody
import okio.Buffer
import retrofit2.Converter
import java.io.OutputStreamWriter
import java.io.Writer
import java.nio.charset.StandardCharsets.UTF_8


/**
 * @author
 * @description:
 * @date :2024/4/3
 * @version 1.0.0
 */
class MyGsonRequestBodyConverter<T>(var gson: Gson, var adapter: TypeAdapter<T>) :
    Converter<T, RequestBody> {
    private val MEDIA_TYPE = MediaType.get("application/json; charset=UTF-8")
    override fun convert(value: T): RequestBody {
        val buffer = Buffer()
        val writer: Writer = OutputStreamWriter(buffer.outputStream(), UTF_8)
        val jsonWriter: JsonWriter = gson.newJsonWriter(writer)
        jsonWriter.isLenient = true
        adapter.write(jsonWriter, value)
        jsonWriter.close()
        return RequestBody.create(MEDIA_TYPE, buffer.readByteString())
    }


}